#!/usr/bin/env python
"""
Standard way of logging across all Leo Goodstadt's programmes
"""
import sys

import logging
import logging.handlers

MESSAGE = 15
logging.addLevelName(MESSAGE, "MESSAGE")

def setup_std_logging (logger, log_file, verbose):
    """
    set up logging using programme options
    """
    class debug_filter(logging.Filter):
        """
        Ignore INFO messages
        """
        def filter(self, record):
            return logging.INFO != record.levelno

    class NullHandler(logging.Handler):
        """
        for when there is no logging
        """
        def emit(self, record):
            pass

    # We are interesting in all messages
    logger.setLevel(logging.DEBUG)
    has_handler = False

    # log to file if that is specified
    if log_file:
        handler = logging.FileHandler(log_file, delay=False)
        class stripped_down_formatter(logging.Formatter):
            def format(self, record):
                prefix = ""
                if not hasattr(self, "first_used"):
                    self.first_used = True
                    prefix = "\n" + self.formatTime(record, "%Y-%m-%d")
                    prefix += " %(name)s\n" % record.__dict__
                if record.levelname in ("INFO", "MESSAGE", "DEBUG"):
                    self._fmt = " %(asctime)s - %(message)s"
                else:
                    self._fmt = " %(asctime)s - %(levelname)-7s - %(message)s"
                return prefix + logging.Formatter.format(self, record)
        handler.setFormatter(stripped_down_formatter("%(asctime)s - %(name)s - %(levelname)6s - %(message)s", "%H:%M:%S"))
        handler.setLevel(MESSAGE)
        logger.addHandler(handler)
        has_handler = True

    # log to stderr if verbose
    if verbose:
        stderrhandler = logging.StreamHandler(sys.stderr)
        stderrhandler.setFormatter(logging.Formatter("    %(message)s"))
        stderrhandler.setLevel(logging.DEBUG)
        if log_file:
            stderrhandler.addFilter(debug_filter())
        logger.addHandler(stderrhandler)
        has_handler = True

    # no logging
    if not has_handler:
        logger.addHandler(NullHandler())



#_________________________________________________________________________________________

#   getLogger

#_________________________________________________________________________________________
def getLogger (module_name, log_file, verbose):
    """
    Convenience function which also sets things up
    """
    logger = logging.getLogger(module_name)
    setup_std_logging(logger, log_file, verbose)
    return logger

#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Testing


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888


#
#   debug code not run if called as a module
#
if __name__ == '__main__':
    import unittest, os
    #       self.assertEqual(self.seq, range(10))
    #       self.assert_(element in self.seq)
    #       self.assertRaises(ValueError, random.sample, self.seq, 20)
    class Test_adjacent_iter(unittest.TestCase):
        def setUp (self):
            if not os.path.exists("temp_logging"):
                os.makedirs("temp_logging")

        def test_function(self):
            """
                test
            """
            #
            #   file output is indiscriminate
            #
            #   debug output depends on verbose
            #
            #


            loggers = []
            loggers.append(getLogger("test0", "temp_logging/test1.log", 0))
            loggers.append(getLogger("test1", "temp_logging/test2.log", 1))
            loggers.append(getLogger("test2", None,                     0))
            loggers.append(getLogger("test3", None,                     1))
            for i in range(4):
                loggers[i].error("logger %d error test" % i)
                loggers[i].debug("logger %d debug test" % i)
                loggers[i].log(MESSAGE, "logger %d message test" % i)


    if sys.argv.count("--debug"):
        sys.argv.remove("--debug")
    unittest.main()




